package com.devoneilers.androidworldfactbook;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class FactSelectActivity extends Activity 
{
	ArrayList<String> countries;
	ArrayList<String> categories;
	WFBTable table;
	CIAWorldFactbook wfb;
	boolean countrySelected;
	boolean categorySelected;
	boolean factSelected;
	boolean worldSelected;
	boolean listPopulated;
	boolean factFound;
	HashMap<String,String> categoryAndFacts;
	Spinner countryMenu;
	Spinner categoryMenu;
	Spinner factMenu;
	ProgressDialog progressDialog;
	ProgressDialog dialog;
	TextView loading;
	Button getFact;
	String fact;
    @TargetApi(9)
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fact_select);
        loading = (TextView) findViewById(R.id.loading);
        loading.setVisibility(View.INVISIBLE);
        countries = new ArrayList<String>();
        categories = new ArrayList<String>();
        countrySelected = false;
        categorySelected = false;
        factSelected = false;
        worldSelected = false;
        listPopulated = false;
        factFound = false;

        try 
        {
        	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        	StrictMode.setThreadPolicy(policy);
        	
			table = new WFBTable();
			wfb = new CIAWorldFactbook();
		} 
        catch (IOException e) 
		{
			e.printStackTrace();
		}
        
        new GetCountryList().execute();  
        countryMenu = (Spinner) findViewById(R.id.country_select);
        categoryMenu = (Spinner) findViewById(R.id.category_select);
        factMenu = (Spinner) findViewById(R.id.fact_select);
        getFact = (Button) findViewById(R.id.get_fact);
        
        countryMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
        {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) 
			{
				if (countryMenu.getSelectedItem().equals("Select A Country"))
				{
					countrySelected = false;
				}
				else if (countryMenu.getSelectedItem().equals("World"))
				{
					categoryAndFacts = wfb.worldFactTypeList;
					countrySelected = true;
					worldSelected = true;
				}
				else
				{
					categoryAndFacts = wfb.countryFactTypeList;
					countrySelected = true;
				}
				
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// do nothing?
			}

		
        	
        });
        
        categoryMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
        {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) 
			{
				if (categoryMenu.getSelectedItem().equals("Select A Category"))
				{
					categorySelected = false;
				}
				
				if (listPopulated)
				{
					categories.removeAll(categories);
					categories.add("Select A Category");
				}
				
				try {
					populateWorldOrCountry(worldSelected, (String) categoryMenu.getSelectedItem(), R.id.fact_select);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				categorySelected = true;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
        	
		});
		
        factMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
        {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) 
			{
				factSelected = true;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
        	
		});
        
        getFact.setOnClickListener(new View.OnClickListener() 
        {
			
			public void onClick(View v) 
			{
				factFound = false;
				progressDialog = ProgressDialog.show(v.getContext(), "Retreiving Fact", "Loading");

				new GetFact().execute();

								
			}
		});
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_fact_select, menu);
        return true;
    }
    
    private void addToSpinner(ArrayList<String> arr, int spinnerHexId)
    {
    	Spinner s = (Spinner) findViewById(spinnerHexId);
    	String[] temp = arraylistToArray(arr);
    	
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, temp);
    	
    	s.setAdapter(adapter);
    }
    
    private void addToSpinner(String[] arr, int spinnerHexId)
    {
    	Spinner s = (Spinner) findViewById(spinnerHexId);

    	
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arr);
    	
    	s.setAdapter(adapter);
    }
    
    private static String[] arraylistToArray(ArrayList<String> arr)
    {
    	String[] temp = new String[arr.size()];
    	
    	for (int i = 0; i < arr.size(); ++i)
    	{
    		temp[i] = arr.get(i);
    	}
    	
    	return temp;
    }
    
    private static String[] populateList(String factList) throws FileNotFoundException
    {
        Scanner scan = new Scanner(factList);
        ArrayList<String> list = new ArrayList<String>();
        while (scan.hasNext())
        {
            list.add(scan.nextLine().trim());
                    
        }
        
        String[] temp = arraylistToArray(list);
        
        
        return temp;
    }
    
    private void populateWorldOrCountry (boolean isWorld, String selectedItem, int spinnerHexId) throws FileNotFoundException
    {
    	if (!isWorld)
    	{
    		for (Map.Entry<String, String> entry : wfb.countryFactTypeList.entrySet())
    		{
    			if (entry.getKey().equals(selectedItem))
    			{
    				String[] factListArr = populateList(Lists.getList(entry.getValue()));
    				
    				addToSpinner(factListArr, spinnerHexId);
    				
    				listPopulated = true;
    				categorySelected = true;
    				break;
    			}
    		}
    	}
    	else
    	{
    		for (Map.Entry<String, String> entry : wfb.worldFactTypeList.entrySet())
    		{
    			if (entry.getKey().equals(selectedItem))
    			{
    				String[] factListArr = populateList(Lists.getList(entry.getValue()));
    				addToSpinner(factListArr, spinnerHexId);
    				
    				listPopulated = true;
    				categorySelected = true;
    				break;
    			}
    		}
    	}
    }
    
    private class GetCountryList extends AsyncTask<Void, Integer, Void>
    {
    	
    	@Override
    	protected Void doInBackground(Void... params) {
            
            countries.add("Select A Country");
            
            for (String s : table.getCountries())
            {
            	countries.add(s);
            }
			return null;
    		
    	}
    	
    	protected void onProgressUpdate(Integer... progress)
    	{
    		super.onProgressUpdate(progress);
    	}
    	
    	protected void onPostExecute(Void result)
    	{
    		super.onPostExecute(result);
    		
            if (countries == null)
            {
            	Toast toast = Toast.makeText(getApplicationContext(), "Your internet sucks", Toast.LENGTH_LONG);
            	toast.show();
            }
            else
            {
            	addToSpinner(countries, R.id.country_select);
            }
            
            categories.add("Select A Category");
            for (String s : wfb.countryFactTypeList.keySet())
            {
            	categories.add(s);
            }
            
            addToSpinner(categories, R.id.category_select);
    	}
    	

    }
    
    private class GetFact extends AsyncTask<Void, Integer, Void>
    {

		

		@Override
		protected Void doInBackground(Void... params) 
		{
			String selectedFact = (String) factMenu.getSelectedItem();
			String countryCode = wfb.getCountryCodeList().get((String) countryMenu.getSelectedItem());
			try 
			{
				fact = wfb.getCountryFact(countryCode, selectedFact);
				
				if (fact==null)
				{
					fact = "No data found";
				}
			} catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
    	
		protected void onProgressUpdate(Integer... progress)
		{
			super.onProgressUpdate(progress);
		}
		
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			progressDialog.dismiss();
			
			Intent intent = new Intent(getApplicationContext(), FactDisplayActivity.class);
			intent.putExtra("FACT_RETRIEVED", fact);
			startActivity(intent);
		}
    }
}


